
var app = getApp();
var c = require("../libs/common.js");
var cf = require('../libs/config.js');
import TIM from '../libs/tim-wx-sdk';
import COS from '../libs/cos-wx-sdk-v5';
let options = {
  SDKAppID: 1400133121 // 接入时需要将 0 替换为您的云通信应用的 SDKAppID
};
// 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
let tim = TIM.create(options); // SDK 实例通常用 tim 表示
app.globalData.tim = tim;
app.globalData.TIM = TIM;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      'http://wyk-img-1255995999.cos.ap-beijing.myqcloud.com/user/php1.png',
      'http://wyk-img-1255995999.cos.ap-beijing.myqcloud.com/user/php201053486094251370.png',
      'http://wyk-img-1255995999.cos.ap-beijing.myqcloud.com/user/php775452032144384041.png'
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.getHomeInfo(that);//首页获取值 并赋值
    var uid = wx.getStorageSync('userinfo').id;
    that.showLoadingFun('获取IM信息...'); 
    that.getImLoginInfo(uid);//小程序登录成功之后im登录 需要先从接口获取信息
    if(uid){//如果用户已经登录需要做im登录循环
      // c.reRun('getImLoginInfo', that, 2,function(){
      //   console.log('超过2秒了 需要从新加载getImLoginInfo');
      //   that.getImLoginInfo(uid);
      //   wx.setStorageSync('getImLoginInforeRun', 1);//如果成功则需要终止 循环调用此方法
      // });
    }
    that.loginOut();//登出
  },

   //获取首页信息
   getHomeInfo:function(that){
     c.ajax(
       cf.hostapi + 'Home/Home',
       {},
       res => {
         var Banners = res.data.data.Banners;
         var Knowledge = res.data.data.Knowledge;
         console.log(Knowledge);
         that.setData({ imgUrls: Banners, Knowledge: Knowledge })
       }
     )
   },

   //showLoading
  showLoadingFun:function(info){
    wx.showLoading({
      title: info,
      mask: true,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    }) 
  },


loginOut:function(){
  //一个账号只能一个设备登录 监听其他账号登录 这个账号就 被踢
  let onKickedOut = function (event) {
    console.log('退出成功');
    console.log(event.data.type);
    wx.setStorageSync('userinfo', '');
    wx.redirectTo({
      url: '/pages/login/login',
    })
    // 1.TIM.TYPES.KICKED_OUT_MULT_ACCOUNT(Web端，同一账号，多页面登录被踢)
    // 2.TIM.TYPES.KICKED_OUT_MULT_DEVICE(同一账号，多端登录被踢)
  };

  tim.on(TIM.EVENT.KICKED_OUT, onKickedOut);
},

  
//im登录     //如果用户小程序已经登录则需要IM登录
  getImLoginInfo:function(uid){
    //获取using数据
    var that=this;
    if (uid) {
      c.ajax(
        cf.hostapi + 'Im/getLoginInfo', {
          uid: uid
        },
        res => {
          var loginInfo = res.data.data;
          console.log('loginInfo');
          console.log(loginInfo);
          var userSig = loginInfo.userSig;
          // IM开始登录
          wx.hideLoading();
          that.showLoadingFun('创建登录链接...');
          //IM登录
          that.logIm(uid, userSig);
          // c.reRun('logIm', that, 2,function(that){
          //   console.log('超过2秒了 需要从新加载logIm');
          //   that.logIm(uid, userSig);
          //   wx.setStorageSync('logImreRun', 1);//如果成功则需要终止 循环调用此方法
          // });


        }
      )
    } else {
      wx.redirectTo({
        url: '/pages/login/login',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },

//IM登录
  logIm: function (uid, userSig){
  var that=this;
  var promises = tim.login({ userID: uid, userSig: userSig });
  console.log('promises');
  console.log(promises);
  promises.then(function (imResponse) {
    if (imResponse.data.actionStatus) {
      console.log('IM登录成功');
      wx.hideLoading();
      that.showLoadingFun('获取会话列表...');
      
      that.getMeList();
      // c.reRun('getMeList', that, 2,function(that){
      //   console.log('超过2秒了 需要从新加载getMeList');
      //   that.getMeList();
      //   wx.setStorageSync('getMeListreRun', 1);//如果成功则需要终止 循环调用此方法
      // });

    }; // 登录成功
  }).catch(function (imError) {
    console.warn('login error:', imError); // 登录失败的相关信息
    console.log('IM登录失败');
  });
},

test:function(){
  // 监听事件，如：
  tim.on(TIM.EVENT.SDK_READY, function (event) {
    // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
    // event.name - TIM.EVENT.SDK_READY
    // 将某会话下所有未读消息已读上报
    let promise = tim.setMessageRead({ conversationID: 'C2C5' });
    promise.then(function (imResponse) {
      // 已读上报成功
      console.log('已读上报成功');
    }).catch(function (imError) {
      // 已读上报失败
      console.log('已读上报失败');
      console.warn('setMessageRead error:', imError);
    });
  });



},


  getMeList: function () {
    console.log('进入');
    // 监听事件，如：
    var that = this;
    tim.on(TIM.EVENT.SDK_READY, function (event) {
      that.getList();
    });
  },
   
   getList:function(){
     // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
     // event.name - TIM.EVENT.SDK_READY
     // 拉取会话列表
     let promiselist = tim.getConversationList();
     promiselist.then(function (imResponse) {
       const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表

       console.log('conversationList'); 
       console.log(conversationList);


       var arr = Object.keys(conversationList);
       wx.hideLoading();
       var unred = 0;
       for (let i = 0; i < arr.length; i++) {
         console.log(conversationList[i]);
         unred += conversationList[i]['unreadCount'];
       }

       var unred = unred.toString();
       if (unred==0){
         unred='';
       }
       if (unred){
         wx.setTabBarBadge({
           index: 1,
           text: unred
         })
       }else{
         wx.setTabBarBadge({
           index: 1,
         })
       }
     }).catch(function (imError) {
       console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
     });
   },


  getkid:function(e){
    var kid=e.currentTarget.dataset.kid;
    wx.navigateTo({
      url: '/pages/petknow/petknow?kid=' + kid,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //计算发布过来未读数量
    let onMessageReceived = function (event) {
      that.getList();
    };
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  jumpurl:function(e){
    var url=e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/' + url + '/' + url,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  hotmore:function(){
    wx.navigateTo({
      url: '/pages/newsmore/newsmore',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  }
})